<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 * @author ml
 * @date 2017-10-19
 */
class Quantification extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('M_user');
        $this->load->model('M_quantification_user');
        $this->load->model('M_quantification_user_map');
        $this->load->model('M_quantification_user_map_add');
    }

    /**
     * 用户的量化任务
     */
    public function userQuantification(){
        //分为干部量化任务，和职工量化任务
        //测试职工的量化任务
        $PID = getParam($this->input->get_post("userid", true), 'int');//用户id
        $type = getParam($this->input->get_post("status", true), 'int',1);//1执行中的任务  2已完成  3全部任务
        $workid = getParam($this->input->get_post("workid", true), 'int',0);//岗位ID
        $size 	= getParam($this->input->get_post("size", true), 'int', 10);  //条数
        $page 	= getParam($this->input->get_post("page", true), 'int', 1);  //页数
        $start_time = getParam($this->input->get_post("starttime", true), 'string',"");  //页数
        $end_time 	= getParam($this->input->get_post("endtime", true), 'string',"");  //页数
//        $is_leader = getParam($this->input->get_post("isleader", true), 'int',0);// 1 职工 2 干部
        $is_leader = $this->M_user->getOne('user_level',array('user_id'=>$PID));
//        $PID= 67;
//        $type=1;
//        $workid=2;
        if(empty($PID)) exit(json_encode(array('code'=>1,'data'=>'','info'=>'参数不全')));

        $where = array();
        $tables = array('t_quantification_user_map' => 'qm', 't_quantification_user' => 'qu','t_grid'=>'m','t_quantification'=>'q');
        $join = array('qm.quantification_user_id=qu.quantification_user_id','qm.grid_id = m.grid_id','qu.quantification_id =q.quantification_id');
//        $where['qm.user_id'] =$PID;
//        $where['qm.is_del'] = 1;
        $time = time();
//        $time = 1507618822;
        if($start_time!="")
        {
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time);
            if($end_time>$time)
            {
                $end_time=$time;
            }
        }
        else
        {
            $year = date('Y');
            $month = date('m');
            $m1 = $year."-".$month;
            $start_time = strtotime($m1);//strtotime($m1);//指定月份月初时间戳
            $end_time = $time;
        }


        if($type == 1 || $type == 2){
            $where['qm.status'] = ($type == 1) ? "1" : "2";
            if($workid==0)
            {
                $where['q.quantification_post_type<='] = 2;
            }
            else
            {
                $where[" (q.quantification_post_type<=2 or (q.quantification_post_type=3 AND q.quantification_user=$workid)) "] = null;
            }
            $where['qm.user_id'] =$PID;
            $where['qm.is_del'] = 1;
            if($type ==2)
            {
                $where['qm.start_time <='] = $time;
                $where['qm.start_time >='] = $start_time;
            }
            else
            {
                $where['qm.start_time <='] = $time;
                $where['qm.end_time >='] = $time;
            }
            $orderby = "";
        }
        else{
            $where["(qm.end_time <=$time AND qm.start_time <=$start_time and qm.end_time >=$start_time and qm.user_id=$PID and qm.is_del=1) or (qm.end_time <=$time AND qm.start_time <=$end_time and qm.end_time >=$end_time and qm.user_id=$PID and qm.is_del=1) or (qm.end_time <=$time AND qm.start_time >= $start_time and qm.end_time <=$end_time and qm.user_id=$PID and qm.is_del=1) "] = null;
//            $where['qm.end_time >='] = $start_time.") ";
//            $where['qm.start_time <='] = $end_time;
//            $where['qm.end_time >='] = $end_time;

            $orderby = "qm.start_time desc";
        }
        $limit  = ($page - 1) * $size;
        $data   = array('total_page' => "0", 'list' => array());
        $count  = $this->M_quantification_user_map->getJoinList($tables, $join, 'Count(*)',$where);
        $count  = $count[0]['Count(*)'];
//        if(empty($count))  $this->printJson_data($data);
        $data['total_page'] = ceil($count / $size);
        $field = 'qm.*,q.quantification_name,m.grid_name,qu.quantification_user_remark,qu.quantification_user_status as qustatus';
        $list = $this->M_quantification_user_map->getJoinList($tables, $join, $field, $where, $size, $limit, $orderby);
        $to_list =array();
        if(!empty($list)) {
            foreach ($list as $k => $v) {
                $to_list[$k] = array(
                    'id' => $v['quantification_user_map_id'],
                    'title' => $v['grid_name'],  //网格名称
                    'name' => $v['grid_name'],   //任务名称
                    'time' => date('Y-m-d H:i:s', $v['start_time']) . ' - ' . date('Y-m-d H:i:s', $v['end_time']),  //时间段
                    'start_time'=>date('Y-m-d H:i', $v['start_time']),
                    'end_time'=>date('Y-m-d H:i', $v['end_time']),
                    'status' => $v['status'],  //1 未完成 2 已完成
                    'number'=>$v['number'],   //次数
                    'finish_number'=>$v['finish_number'], //已完成次数
                    'remark'=>$v['quantification_user_remark'],   //备注10.78.153.155
                    'type'  =>$v['type'],     //1 未请假  2 请假
                );
                if($v['qustatus'] == 1){
                    $to_list[$k]['start_time'] = date('Y-m-d', $v['start_time']);
                    $to_list[$k]['end_time'] = date('Y-m-d', $v['end_time']);
                }

            }

            $data['list'] = $to_list;
        }
        //查看已完成，不需要下面步骤
        if($type==1)
        {
            //当前任务总数
            unset($where['qm.status']);
            if($is_leader==2)
            {
                unset($where['qm.start_time <=']);
                unset($where['qm.end_time >=']);
                $nian = date("Y");
                $yue = date("m");
                $where['FROM_UNIXTIME(qm.start_time,\'%Y\')']= $nian;
                $where['FROM_UNIXTIME(qm.start_time,\'%m\')']= $yue;
            }
            $total  = $this->M_quantification_user_map->getJoinList($tables, $join, 'Count(*) as count,count(IF(qm.status=2,1,null)) as num',$where);
            $count1 = $total[0]['num'];
            $data['count'] = $count1;//本月已完成任务
            if($is_leader==2)//干部统计总数
            {
                $total = $total[0]['count'];
                $data['total'] = $total;//本月总任务
                $data['un_count']=$total-$count1;//本月待完成量化任务
            }
            else//职工统计总数
            {
                if($count==0)
                {
                    $data['total'] = 0;//已接收量化任务
                    $data['un_count']=0;//当前待完成量化任务
                }
                else
                {
                    $data['total'] = $total[0]['count'];//已接收量化任务
                    $data['un_count']=$count;//当前待完成量化任务
                }
            }
        }
        $this->printJson_data($data);
    }
    //打点
    public function userQuantificationAdd(){
        $task_id = getParam($this->input->get_post("taskid", true), 'int');//任务id
        $PID = getParam($this->input->get_post("userid", true), 'int');//用户id
        $mapid = getParam($this->input->get_post("mapid", true), 'string');//网格id
        $x = getParam($this->input->get_post("x", true), 'string' ,'');//维度
        $y = getParam($this->input->get_post("y", true), 'string' ,'');//经度
        $floor = getParam($this->input->get_post("floor", true), 'string' ,'');//经度
//        $PID= 10;
//        $task_id = 4413;
        $is_leader = $this->M_user->getOne('user_level',array('user_id'=>$PID));//如果是职工则只要有人打点则删除其他相同任务1职工2干部
//        $mapid =1;
//        $x =1;
//        $y=1;
        if(empty($PID) || empty($mapid) || empty($task_id) || empty($x) || empty($y) || empty($floor)) exit(json_encode(array('code'=>1,'data'=>'','info'=>'参数不全')));
        $xiaowangge = $mapid;
        if($mapid){
            $this->load->model('M_t_grid_w');
            $mapid = $this->M_t_grid_w->getOne('grid_id',array('small_grid_id'=>$mapid));
        }

//        $mapid =1;

        if(!$mapid)
        {
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'网格ID错误')));
        }
        $time = time();
        //查询打点是否有效
        $info_list = $this->M_quantification_user_map->getList('quantification_user_map_id,finish_number,number,end_time',array('grid_id'=>$mapid,'user_id'=>$PID,'quantification_user_map_id'=>$task_id,'start_time <='=>$time,'end_time >='=>$time),null,null);
        $user_map_add = $this->M_quantification_user_map_add->getList('add_time',array('user_id'=>$PID,'quantification_user_map_id'=>$task_id),1,null,'add_time desc');

        $data = array(
            'add_x'=>$x,
            'add_y'=>$y,
            'user_id'=>$PID,
            'grid_id'=>$mapid,
            'add_time'=>$time,
            'grid_floor'=>$floor,
            'quantification_user_map_id'=>0,
            'type'=>1,
            'small_grid_id'=>$xiaowangge
        );
        if(!empty($user_map_add))
        {
            if($PID == 3798)//默认写死3798 王杨 9小时多次 以后开发会更改
            {
                if((time()-$user_map_add[0]['add_time']) < 3600 *1)
                {
                    $data['type'] = 3;
                    exit(json_encode(array('code'=>1,'data'=>$data,'info'=>'对不起，您今天已在1小时内在此网格签到！')));
                }
            }
            else
            {
                if((time()-$user_map_add[0]['add_time']) < 3600 *12)
                {
                    $data['type'] = 3;
                    exit(json_encode(array('code'=>1,'data'=>$data,'info'=>'对不起，您今天已在此网格签到！')));
                }
            }
        }
        $qum_id = '0';
        if(!empty($info_list)){
            foreach($info_list as $k=>$v){
                if($time> $v['end_time'])
                {
                    $data['type'] = 3;
                    exit(json_encode(array('code'=>1,'data'=>$data,'info'=>'对不起，您未在规定时间内打点！')));
                }
                $end_number = 0;
                $end_number = $v['finish_number'] + 1;
                $save_data = array('finish_number'=>$end_number);
                if($end_number >= $v['number']){
                    $save_data['status'] = 2;
                }
                //修改任务表状态
                $this->M_quantification_user_map->updateData($save_data,array('quantification_user_map_id'=>$v['quantification_user_map_id']));
//                $qum_id = ','.$v['id'];
                $qum_id =$v['quantification_user_map_id'];
            }
            $data['type']= 2;
            $data['quantification_user_map_id'] = $qum_id;
        }

        if($data['type'] == 1){
            exit(json_encode(array('code'=>1,'data'=>$data,'info'=>'您未在巡检区域内打点！')));
        }else{
            unset($data['type']);
            //插入打点记录
            $istrue = $this->M_quantification_user_map_add->saveData($data);
            if($istrue)
            {
                if($is_leader==1)
                {
                    //删除其他所有相同任务
                    $sql ="select u.quantification_id,um.quantification_map_id,um.grid_id,um.start_time,um.end_time,um.number from t_quantification_user_map um 
                            left join t_quantification_user u on u.quantification_user_id=um.quantification_user_id
                            where um.quantification_user_map_id={$task_id}";
                    $seach = $this->db->query($sql)->row_array();
                    $sql = "select group_concat(um.quantification_user_map_id) id from t_quantification_user_map um 
                            left join t_quantification_user u on u.quantification_user_id=um.quantification_user_id
                            where um.quantification_map_id={$seach['quantification_map_id']} and u.quantification_id={$seach['quantification_id']}
                            and um.grid_id={$seach['grid_id']} and um.start_time={$seach['start_time']} and um.end_time={$seach['end_time']} and um.number={$seach['number']} and um.quantification_user_map_id<>{$task_id}";

                    $res = $this->db->query($sql)->row_array();
                    if(!empty($res['id']))
                    {
                        //逻辑删除
//                        $del_sql ="delete from t_quantification_user_map  where quantification_user_map_id IN({$res['id']})";
                        $del_sql="UPDATE t_quantification_user_map set is_del =2 where quantification_user_map_id IN({$res['id']})";
                        $this->db->query($del_sql);
                    }
                }
                exit(json_encode(array('code'=>0,'data'=>$data,'info'=>'打点成功！')));
            }
            else
            {
                exit(json_encode(array('code'=>1,'data'=>$data,'info'=>'打点失败！')));
            }
        }
        $this->printJson_data($data);
    }

    //每天单点生成线上量化任务（针对岗位）未完成
    function task_start_day($pid,$workid)
    {
//        $pid = getParam($this->input->get_post("userid", true), 'int',0);//用户id
//    $pid=67;
//        $workid = getParam($this->input->get_post("workid", true), 'int',0);//岗位id
//    $workid=2;
    $time = time();
        if(empty($pid) || empty($workid))
        {
            $dd['code'] = 1;
            $dd['info'] ='失败';
            exit(json_encode(array('code'=>1,'info'=>'失败！')));
        }
        $sql = "select q.* from t_quantification q  where q.quantification_post_type=3 and q.is_del=1 and q.quantification_start_time<=$time and q.quantification_user=$workid";
        $quanti = $this->M_quantification_user_map->querylist($sql);
        if(count($quanti)==0)
        {
            exit(json_encode(array('code'=>1,'info'=>'当前岗位无任务！')));
        }
        $dd['info'] = "成功";
        $time = time();
        $n=date("H");
        $n = intval($n);
        //获取当天的年份
        $y = date("Y");
        //获取当天的月份
        $m = date("m");
        //获取当天的号数
        $d = date("d");
        //上线的任务   每天单点 判断是否生成任务
        $tables = array('t_quantification'=>'q','t_quantification_user'=>'u');
        $join = array('q.quantification_id=u.quantification_id');
        $sql1 = "SELECT `q`.*, `u`.`quantification_user_id` as `userid` FROM `t_quantification` As `q` LEFT JOIN `t_quantification_user` As `u` ON `q`.`quantification_id`=`u`.`quantification_id` WHERE `q`.`quantification_post_type` = 3 AND `q`.`is_del` = 1 AND `u`.`user_id` = $pid AND FIND_IN_SET('$workid', q.quantification_user)";
        $user_list = $this->M_quantification_user_map->querylist($sql1);


        if(!empty($user_list)){
            //已生成过当前PID任务
            foreach($user_list as $k=>$v){
                //这个人在这个末班下要做的网格任务
                $user_map  = array();
                $sql = "select * from t_quantification_map where quantification_id=".$v['quantification_id']." and is_del=1";
                $user_map = $this->M_quantification_user_map->querylist($sql);
                if(!empty($user_map)){
                    foreach($user_map as $ak=>$av){
                        //查询当前时间是否已有任务（当前时间段的任务）
                        $tables1 = array('t_quantification_user_map'=>'q');
                        $user_list1 = $this->M_quantification_user_map->getJoinList($tables1,null,'q.*',array('q.quantification_user_id'=>$v['userid'],'q.quantification_map_id'=>$av['quantification_map_id'],'q.grid_id'=>$av['grid_id'],'q.user_id'=>$pid,'q.start_time <='=>$time,'q.end_time>='=>$time),null,null);

                        if(!empty($user_list1))//有当前时间段的任务并且离结束时间大于半小时才会生成任务
                        {
                            continue;
                        }
                        else
                        {

                            //晚上1点到5点之间，2小时频率的要改为4小时频率
                            if((($n >= 1) && ($av['quantification_task_cycle_h'] == 2)) && (($n <=4) && ($av['quantification_task_cycle_h'] == 2)))
                            {
                                $av['quantification_task_cycle_h'] = 4;
                            }

//                        $sql = "SELECT id FROM t_quantification_user_map WHERE qu_user_id=".$v['userid']." and qu_map_id=".$av['map_id']." and PID=".$pid;
//                        $count = $this->M_quantification_user_map->querylist($sql);
//                        $count = count($count)+1;
                            $h = ($n-1)/$av['quantification_task_cycle_h'];
                            $h = floor($h);
//                        $h = intval($h);
                            $h = $av['quantification_task_cycle_h']*$h+1;
//                        $h=($av['h']*$count)+1;
                            $todayTime= mktime($h,0,0,$m,$d,$y);
                            //计算结束时间
                            $map_time_i = ($av['quantification_task_cycle_d'] * 24 * 60) + ($av['quantification_task_cycle_h'] * 60);
                            $map_time_jiange = $map_time_i * 60;// 间隔时间 秒
                            $data = array(
                                'quantification_user_id'=>$v['userid'],
                                'quantification_map_id'=>$av['quantification_map_id'],
                                'grid_id'=>$av['grid_id'],
                                'start_time'=>$todayTime,
                                'end_time'=>$todayTime + $map_time_jiange,
                                'number'=>$av['quantification_task_number'],
                                'quantification_user_map_addtime'=>$time,
                                'user_id'=>$pid,
                                'finish_number'=>0,
                            );
//                        if($data['end_time']-$time < 1800)
//                        {
//                            continue;
//                        }
//                        else
//                        {
                            $p = $this->M_quantification_user_map->saveData($data);
                            $dd['info'] = '添加了';
//                                echo "添加";
//                            }
//                            else
//                            {
//                            }
//                        }
                        }
                    }
                }
            }
        }
        else
        {
            foreach ($quanti as $value)
            {
                //还没有生成当前PID的任务
                $data = array(
                    'user_id' =>$pid,
                    'quantification_id' => $value['quantification_id'],
                    'quantification_user_taketime' => $value['quantification_start_time'],
                    'quantification_user_status' => 1,
                    'quantification_user_remark' => '',
                    'quantification_user_check' => $value['quantification_check_cycle'],
                    'quantification_user_addtime' => $time,
                );
                //用户每月任务
                $rid = $this->M_quantification_user->saveData($data);
                $user_map  = array();
                $sql = "select * from t_quantification_map where quantification_id=".$value['quantification_id']." and is_del=1";
                $user_map = $this->M_quantification_user_map->querylist($sql);
                foreach($user_map as $ak=>$av){
                    //晚上1点到5点之间，2小时频率的要改为4小时频率
                    if((($n >= 1) && ($av['quantification_task_cycle_h'] == 2)) && (($n <=4) && ($av['quantification_task_cycle_h'] == 2)))
                    {
                        $av['quantification_task_cycle_h'] = 4;
                    }

                    $h = ($n-1)/$av['quantification_task_cycle_h'];
                    $h = floor($h);
//              $h = intval($h);
                    $h = $av['quantification_task_cycle_h']*$h+1;

                    $todayTime= mktime($h,0,0,$m,$d,$y);
                    //获取当前的时间（几点$n）
                    //计算结束时间
                    $map_time_i = ($av['quantification_task_cycle_d'] * 24 * 60) + ($av['quantification_task_cycle_h'] * 60);
                    $map_time_jiange = $map_time_i * 60;// 间隔时间 秒
                    $data = array(
                        'quantification_user_id'=>$rid,
                        'quantification_map_id'=>$av['quantification_map_id'],
                        'grid_id'=>$av['grid_id'],
                        'start_time'=>$todayTime,
                        'end_time'=>$todayTime + $map_time_jiange,
                        'number'=>$av['quantification_task_number'],
                        'finish_number'=>0,
                        'quantification_user_map_addtime'=>$time,
                        'user_id'=>$pid,
                    );

//                if($data['end_time']-$time < 1800)
//                {
//                    continue;
//                }
//                else
//                {
                    $p = $this->M_quantification_user_map->saveData($data);
                    $dd['info'] = '添加了';
//                }
//            echo "添加";
                }
            }
        }
        exit(json_encode(array('code'=>0,'info'=>$dd['info'])));
//        $this->printJson_data($dd);
    }
    //记录位置信息
    public function addMap(){
        $PID = $this->input->get_post("PID", true);//用户id
        $floor = $this->input->get_post("floor", true);//楼层
        $mapid =  $this->input->get_post("mapid", true);//地图标识
        $map_id = $this->input->get_post("map_id", true);//所属网格标示
        $x = $this->input->get_post('x',true);//x
        $y= $this->input->get_post('y',true);//y
        $age = getParam($this->input->get_post("age", true), 'string' ,'');//age    string
        //$age = $this->input->get_post('age',true);//age	string	定位时间距离当前时间的差值
        $mac = $this->input->get_post('mac',true);//age	string	定位时间距离当前时间的差值
        $wname = $this->input->get_post("wname", true);//楼层
        if(empty($PID) || empty($floor) || empty($mapid) || empty($x) || empty($y) || empty($mac)){
            exit(json_encode(array('code'=>2001,'data'=>array(),'info'=>'参数不全！')));
        }
        if($map_id){
            $this->load->model('M_t_grid_w');
            $map_id = $this->M_t_grid_w->getOne('t_grid_id',array('id'=>$map_id));
        }
        $data = array(
            'PID'=>$PID,
            'floor'=>$floor,
            'mapid'=>$mapid,
            'map_id'=>$map_id,
            'x'=>$x,
            'y'=>$y,
            'add_time'=>time(),
            'age'=>$age,
            'mac'=>$mac,
            'wname'=>$wname,
        );
        $this->load->model('M_t_bjnz_user_map_copy');
        $this->M_t_bjnz_user_map_copy->saveData($data);
        $this->printJson_data($data);

    }
}